package com.github.bridge.util;

import cn.hutool.extra.spring.SpringUtil;
import com.github.bridge.client.esign.request.CommonHerder;
import com.github.bridge.handler.SysConfigHandler;
import lombok.experimental.UtilityClass;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: signature-bridge-service
 * @description: e签宝工具
 * @author: hui.zhang
 * @date: 2024/8/25 11:11 上午
 **/

@UtilityClass
public class ESignUtil {

    public CommonHerder signBody(String projectId, String bodyStr) {
        // 查询projectId对应的secret
        CommonHerder commonHerder = new CommonHerder();
        commonHerder.setProjectId(projectId);
        SysConfigHandler sysConfigHandler = SpringUtil.getBean(SysConfigHandler.class);
        String secret = sysConfigHandler.findSecretBySystemId(projectId);
//        String secret = "IQ2G11ZABOS4heoA";
        byte[] bytes = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, secret).hmac(bodyStr);
        String signature = new String(Hex.encodeHex(bytes));
        commonHerder.setSignature(signature);
        return commonHerder;
    }

    public CommonHerder signQuery(String projectId, Map<String, String> map) {
        // 查询projectId对应的secret
        CommonHerder commonHerder = new CommonHerder();
        commonHerder.setProjectId(projectId);
        SysConfigHandler sysConfigHandler = SpringUtil.getBean(SysConfigHandler.class);
        String secret = sysConfigHandler.findSecretBySystemId(projectId);
//        String secret = "IQ2G11ZABOS4heoA";
        // 将map转换成 key=value&key=value
        String bodyStr = map.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.joining("&"));
        byte[] bytes = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, secret).hmac(bodyStr);
        String signature = new String(Hex.encodeHex(bytes));
        commonHerder.setSignature(signature);
        return commonHerder;
    }
}
